package awesome.Threading;

import java.util.Vector;
import java.util.concurrent.PriorityBlockingQueue;

import awesome.Manager.ItemManager;
import awesome.Manager.UserManager;
import awesome.mail.MailInterface;


public class BidThreadManager extends Thread {
	private PriorityBlockingQueue<Vector> devQueue = new PriorityBlockingQueue<Vector>(1, new priQueueComparator());
	
	
	public void run()
	{
		while(true)
		{
			if(!devQueue.isEmpty())
			{
				Vector d = devQueue.remove(); 
				
				if(System.currentTimeMillis() > (Long)d.get(1))
				{
					if(d.get(2) == null)
					{
						System.out.println("complete action 1");
					}
				
					else
					{
						System.out.println("This is a place to send text Message. ");
						sendText(Integer.parseInt(d.get(0).toString()),
								Integer.parseInt(d.get(2).toString()),d.get(4).toString());
					}
					
					
				while((System.currentTimeMillis() > ((Long)d.get(1))) && !devQueue.isEmpty())
					{	
						d = devQueue.remove(); 
						
						if(System.currentTimeMillis() > (Long)d.get(1))
						{
							if(d.get(2) == null)
							{
								//System.out.println("Sleep Complete: Reconnecting Device");
								System.out.println("complete action 2");
							}
							else
							{
								System.out.println("This is a place to send text Message. ");
								sendText(Integer.parseInt(d.get(0).toString()),
										Integer.parseInt(d.get(2).toString()),d.get(4).toString());
							}
						}
						else
						{	
							devQueue.add(d);
						}
					}
				}
				else
				{
					long val = ((Long)d.get(1) - System.currentTimeMillis());

					devQueue.add(d);
					
					if(val > 0)
					{
						try {
							Thread.sleep(val);
						} catch (InterruptedException e) {
	
						}
					}
				}
			}
			else
			{
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				
				}
			}
		}
	}
	
	
	
	private void sendText(int uid, int iid, String itemName) {
		UserManager um = new UserManager();
		Vector v = um.getNameAndPhone(uid);
		
		String name = v.get(0).toString();
		String phone = v.get(1).toString();
		
		String message = name +", you won the bid for " + itemName;
		
		MailInterface.sendTextMessage(phone, message);
	}



	public void addBid(int uid, int iid, float amount)
	{
		System.out.println("added to Bid Thread Manager");
		
		Vector v = new Vector();
		ItemManager im = new ItemManager();
		long timeStamp = im.getTimeStamp(iid);
		String name = im.getName(iid);
		v.add(uid);
		v.add(timeStamp);
		v.add(iid);
		v.add(amount);
		v.add(name);
		devQueue.add(v);
		
		this.interrupt(); 
	}
	
	public static void main(String[] args)
	{
		new BidThreadManager().sendText(16,
				31,"item name");
	}
}
